package com.uxsino.reactorq;

import javax.jms.DeliveryMode;
import javax.jms.InvalidDestinationException;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TemporaryQueue;

/**
 * Customized version of javax.jms.QueueRequester
 * with timeout feature
 * 
 *
 */
public class QueueRequester {
    private QueueSession session;

    private TemporaryQueue temporaryQueue;

    private QueueSender sender;

    private QueueReceiver receiver;

    public QueueRequester(Session session, Queue queue) throws JMSException {

        if (queue == null) {
            throw new InvalidDestinationException("Invalid queue");
        }

        this.session = (QueueSession) session;
        setTemporaryQueue(session.createTemporaryQueue());
        QueueSender sender = this.session.createSender(queue);
        sender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        setSender(sender);
        setReceiver(this.session.createReceiver(getTemporaryQueue()));
    }

    public Message request(Message message, long millisTimeout) throws JMSException {
        message.setJMSReplyTo(getTemporaryQueue());
        getSender().send(message);
        return getReceiver().receive(millisTimeout);
    }

    public void close() throws JMSException {
        getSession().close();
        getTemporaryQueue().delete();
    }

    private void setReceiver(QueueReceiver receiver) {
        this.receiver = receiver;
    }

    private QueueReceiver getReceiver() {
        return receiver;
    }

    private void setSender(QueueSender sender) {
        this.sender = sender;
    }

    private QueueSender getSender() {
        return sender;
    }

    private QueueSession getSession() {
        return session;
    }

    private void setTemporaryQueue(TemporaryQueue temporaryQueue) {
        this.temporaryQueue = temporaryQueue;
    }

    private TemporaryQueue getTemporaryQueue() {
        return temporaryQueue;
    }
}